package org.appfuse.dao.hibernate;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.appfuse.dao.hibernate.BaseDaoHibernate;
import org.appfuse.model.Menu;
import org.appfuse.dao.MenuDao;

import org.springframework.orm.ObjectRetrievalFailureException;

public class MenuDaoHibernate extends BaseDaoHibernate implements MenuDao {

	/**
	 * @see org.appfuse.dao.MenuDao#getMenus(org.appfuse.model.Menu)
	 */
	public List getMenus(final Menu menu) {
		// return getHibernateTemplate().find("from Menu");

		if (menu == null || StringUtils.isBlank(menu.getName())) {
			return getHibernateTemplate().find("from Menu order by id");
		}
		List menus = getHibernateTemplate().find("from Menu where parentName = '" + menu.getName() + "' order by id");
		return getHibernateTemplate().find("from Menu where parentName = '" + menu.getName() + "' order by id");

		/*
		 * Remove the line above and uncomment this code block if you want to
		 * use Hibernate's Query by Example API. if (menu == null) { return
		 * getHibernateTemplate().find("from Menu"); } else { // filter on
		 * properties set in the menu HibernateCallback callback = new
		 * HibernateCallback() { public Object doInHibernate(Session session)
		 * throws HibernateException { Example ex =
		 * Example.create(menu).ignoreCase().enableLike(MatchMode.ANYWHERE);
		 * return session.createCriteria(Menu.class).add(ex).list(); } }; return
		 * (List) getHibernateTemplate().execute(callback); }
		 */
	}

	/**
	 * @see org.appfuse.dao.MenuDao#getMenu(Long id)
	 */
	public Menu getMenu(final Long id) {
		Menu menu = (Menu) getHibernateTemplate().get(Menu.class, id);
		if (menu == null) {
			log.warn("uh oh, menu with id '" + id + "' not found...");
			throw new ObjectRetrievalFailureException(Menu.class, id);
		}

		return menu;
	}

	/**
	 * @see org.appfuse.dao.MenuDao#saveMenu(Menu menu)
	 */
	public void saveMenu(final Menu menu) {
		getHibernateTemplate().saveOrUpdate(menu);
	}

	/**
	 * @see org.appfuse.dao.MenuDao#removeMenu(Long id)
	 */
	public void removeMenu(final Long id) {
		getHibernateTemplate().delete(getMenu(id));
	}
}
